<template>
  <p-form-model ref="form" :model="form" :rules="rules">
    <div class="item">
      <div class="item-left">
        <p-form-model-item
          v-if="showForm"
          :label="label.opportunityNo"
          prop="opportunityNo"
          class="form-item"
        >
          <span>{{ form.opportunityNo }}</span>
        </p-form-model-item>
        <p-form-model-item
          v-if="showForm"
          :label="label.stage"
          prop="stage"
          class="form-item"
        >
          <span>{{ stageOptions[form.stage] }}</span>
        </p-form-model-item>
        <p-form-model-item
          :label="label.opportunityName"
          prop="opportunityName"
          class="form-item"
        >
          <p-input v-model="form.opportunityName" placeholder="请输入" />
          <p-button
            v-if="showCopy"
            v-show="showButton"
            class="copy-clue"
            @click="visibleBusinessList = true"
          >
            复制商机
          </p-button>
        </p-form-model-item>
        <p-form-model-item
          v-if="follow"
          :label="label.customerName"
          class="form-item"
        >
          <span>{{ form.customerName }}</span>
        </p-form-model-item>
        <p-form-model-item
          v-else
          :label="label.customerName"
          prop="customerName"
          class="form-item"
        >
          <p-input
            v-model="form.customerName"
            disabled
            placeholder="请输入"
            style="background-color: #fff; cursor: default; color: #000"
          />
          <InputSearch
            v-show="showButton"
            class="searchIcon"
            :is-edit="true"
            @search="visibleCustomer = true"
          />
        </p-form-model-item>
        <p-form-model-item :label="label.salesGroupName" prop="salesGroupName">
          <p-select
            v-model="form.salesGroup"
            placeholder="请选择"
            :label-in-value="true"
            @change="handleSalesChange"
          >
            <p-select-option
              v-for="(item, key, index) in salesGroup"
              :key="index"
              :value="key"
            >{{ item }}</p-select-option>
          </p-select>
        </p-form-model-item>
        <p-form-model-item :label="label.pmGroup" prop="pmGroup">
          <SelectOrg
            v-model="form.pmGroup"
            :options="orgKapmOptions"
            :has-default="false"
            :allow-clear="true"
            :has-all="false"
            :label-in-value="true"
            @input="handleSelectChange($event, 'pmGroup')"
          />
        </p-form-model-item>
        <p-form-model-item
          :label="label.leadsNo"
          prop="leadsNo"
          class="form-item"
        >
          <p-input
            v-model="form.leadsNo"
            placeholder="请输入"
            disabled
            style="background-color: #fff; cursor: default; color: #000;"
          />
          <InputSearch
            v-if="!form.leadsNo.length || !showForm"
            class="searchIcon"
            :is-edit="true"
            @search="visibleClueList = true"
          />
        </p-form-model-item>
        <p-form-model-item :label="label.expectQuantity" prop="expectQuantity">
          <p-input
            v-model.number="form.expectQuantity"
            placeholder="请输入"
            style="width: 85%"
          />
          (kpcs)
        </p-form-model-item>
        <p-form-model-item :label="label.expectCost" prop="expectCost">
          <span>{{ form.expectCost }}</span>
          (元)
        </p-form-model-item>
        <p-form-model-item :label="label.expectTime" prop="expectTime">
          <p-date-picker
            :value="form.expectTime"
            class="from-input"
            :disabled-date="disabledDate"
            :allow-clear="false"
            placeholder="请选择时间"
            value-format="YYYY-MM-DD"
            @change="handleDeadLineChange"
            @ok="handleDeadLineOk"
          />
        </p-form-model-item>
        <p-form-model-item :label="label.crustItemNo" prop="crustItemNo">
          <p-input v-model="form.crustItemNo" placeholder="请输入" />
        </p-form-model-item>
        <p-form-model-item :label="label.crustItemStep" prop="crustItemStep">
          <p-input v-model="form.crustItemStep" placeholder="请输入" />
        </p-form-model-item>
      </div>
      <div class="item-right">
        <p-form-model-item
          v-if="showForm"
          :label="label.state"
          prop="state"
          class="form-item"
        >
          <span>
            {{ stateOptions[form.state] }}
          </span>
        </p-form-model-item>
        <!-- 商机阶段状态 -->
        <p-form-model-item
          v-if="showForm"
          :label="label.status"
          prop="status"
          class="form-item"
        >
          <span>
            {{ stateStatusOptions[form.stageStatus] }}
          </span>
        </p-form-model-item>
        <p-form-model-item :label="label.salesOrgCode" prop="salesOrgCode">
          <p-select
            v-if="orgList.length !== 1"
            v-model="form.salesOrg"
            placeholder="请选择"
            :label-in-value="true"
            @change="handlechange"
          >
            <p-select-option
              v-for="(item, key, index) in orgGroup"
              :key="index"
              :value="key"
            >{{ item }}</p-select-option>
          </p-select>
          <span v-else>{{ form.salesOrgName }}</span>
        </p-form-model-item>
        <p-form-model-item :label="label.salesAreaName" prop="salesAreaName">
          <span>{{ customerArea[form.salesAreaName] }}</span>
        </p-form-model-item>
        <p-form-model-item
          :label="label.salesName"
          prop="salesName"
          class="form-item"
        >
          <span>{{ form.salesName }}</span>
        </p-form-model-item>
        <p-form-model-item :label="label.pm" prop="pm" class="form-item">
          <!-- <p-input v-model="form.pmName" placeholder="请输入" /> -->
          <SelectUser
            v-model="form.pm"
            :value="text"
            :has-all="false"
            :allow-clear="false"
            :parent-id="form.pmGroup.key"
            @input="handleSelectChange($event, 'pm')"
          />
        </p-form-model-item>
        <p-form-model-item
          :label="label.leadsName"
          prop="leadsName"
          class="form-item"
        >
          <span>{{ form.leadsName }}</span>
        </p-form-model-item>
        <p-form-model-item :label="label.expectPrice" prop="expectPrice">
          <p-input
            v-model.number="form.expectPrice"
            placeholder="请输入"
            style="width: 85%"
          />
          (元/片)
        </p-form-model-item>
        <!-- 预期份额 -->
        <p-form-model-item :label="label.expectShare" prop="expectShare">
          <p-input
            v-model.number="form.expectShare"
            placeholder="请输入百分数"
            style="width: 85%"
          />
          %
        </p-form-model-item>
        <p-form-model-item :label="label.leadsSource" prop="leadsSource">
          <SelectDefault
            v-model="form.leadsSource"
            :has-all="false"
            code="leads_source"
            @input="handleSelectChange($event, 'leadsSource')"
          />
        </p-form-model-item>
        <p-form-model-item :label="label.crustItemName" prop="crustItemName">
          <p-input v-model="form.crustItemName" placeholder="请输入" />
        </p-form-model-item>
        <p-form-model-item :label="label.appCategory" prop="appCategory">
          <SelectDefault
            v-model="form.appCategory"
            placeholder="placeholder"
            :has-all="false"
            code="application"
            @input="handleSelectChange($event, 'appCategory')"
          />
        </p-form-model-item>
      </div>
    </div>
    <p-form-model-item :label="label.competitor" prop="competitor">
      <p-textarea
        v-model="form.competitor"
        style="height: 70px; resize: none"
        placeholder="请输入"
      />
    </p-form-model-item>
    <p-form-model-item :label="label.remark" prop="remark">
      <p-textarea
        v-model="form.remark"
        style="height: 70px; resize: none"
        placeholder="请输入"
      />
    </p-form-model-item>
    <p-form-model-item
      v-if="!showForm"
      :label="label.accessory"
      prop="accessory"
    >
      <p-button @click="upload">
        <p-icon type="upload" />
      </p-button>
      <p-tooltip
        placement="top"
        title="附件上传的格式：xls,
        xlsx,
        doc,
        docx,
        ppt,
        pptx,
        gif,
        png,
        jpg,
        jpeg
        pdf,
        rar,
        zip,"
      >
        <p-icon type="question-circle" style="color: blue; margin-left: 20px" />
      </p-tooltip>
    </p-form-model-item>
    <p-form-model-item>
      <span style="margin-left: 110px; display: block; padding: 3px 0">
        <a v-if="list.length" :href="list[list.length - 1].atthAccessPath">
          {{ list[list.length - 1].atthName }}
        </a>
        <p-icon
          v-show="list.length"
          type="delete"
          style="color: rgb(24, 144, 255); cursor: pointer"
          @click="deleteFile(list)"
        />
      </span>
    </p-form-model-item>
    <div v-if="showForm" class="item">
      <div class="item-left">
        <p-form-model-item
          :label="label.createUserName"
          prop="createUserName"
          class="form-item"
        >
          <span>{{ form.createUserName }}</span>
        </p-form-model-item>
        <p-form-model-item
          :label="label.createDeptName"
          prop="createDeptName"
          class="form-item"
        >
          <span>{{ form.createDeptName }}</span>
        </p-form-model-item>
        <p-form-model-item
          :label="label.updateUserName"
          prop="updateUserName"
          class="form-item"
        >
          <span>{{ form.updateUserName }}</span>
        </p-form-model-item>
      </div>
      <div class="item-right">
        <p-form-model-item
          :label="label.creatTime"
          prop="creatTime"
          class="form-item"
        >
          <span>{{ form.createTime }}</span>
        </p-form-model-item>
        <p-form-model-item
          :label="label.updateTime"
          prop="updateTime"
          class="form-item"
        >
          <span>{{ form.updateTime }}</span>
        </p-form-model-item>
        <p-form-model-item
          :label="label.updateDeptName"
          prop="updateDeptName"
          class="form-item"
        >
          <span>{{ form.updateDeptName }}</span>
        </p-form-model-item>
      </div>
    </div>
    <DialogUserList
      :visible.sync="visibleCustomer"
      :value="value"
      @change="changeCustomer"
    />
    <DialogClueList :visible.sync="visibleClueList" @change="copyClue" />
    <DialogBusinessList
      :visible.sync="visibleBusinessList"
      @change="copyBusiness"
      @number-click="numberInfo"
    />
    <DialogUploadBusiness
      ref="upload"
      type="business"
      :list.sync="list"
      @change="handleInsertChange"
    />
  </p-form-model>
</template>

<script>
import monent from 'moment';
import { getAttachmentDelete } from '@/api/business';
import DialogUserList from '@/components/dialog/DialogUserList.vue';
import DialogBusinessList from '@/components/dialog/DialogBusinessList.vue';
import DialogClueList from '@/components/dialog/DialogClueList.vue';
import DialogUploadBusiness from '@/components/dialog/DialogUploadBusiness.vue';
import SelectUser from '@/components/select/SelectUser.vue';
import { getUserGroup } from '@/api/public.js';
export default {
  components: {
    SelectUser,
    DialogUserList,
    DialogClueList,
    DialogBusinessList,
    DialogUploadBusiness,
  },
  props: {
    form: {
      type: Object,
      default: () => {},
    },
    showForm: {
      type: Boolean,
      default: true,
    },
    follow: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      rules: {
        opportunityName: [
          { required: true, message: '请输入商机名称！', trigger: 'blur' },
          {
            min: 1,
            max: 200,
            message: '长度不能超过200个字符',
            trigger: 'blur',
          },
        ],
        crustItemNo: [
          { max: 255, message: '长度不能超过255个字符', trigger: 'blur' },
        ],
        crustItemName: [
          { max: 255, message: '长度不能超过255个字符', trigger: 'blur' },
        ],
        crustItemStep: [
          { max: 255, message: '长度不能超过255个字符', trigger: 'blur' },
        ],
        itemDemandNum: [
          {
            pattern: /^\+?[1-9]\d*$/,
            message: '请输入一个大于0的整数',
            trigger: 'blur',
          },
          {
            max: 1000000000,
            message: '总量不能超过十亿',
            trigger: 'blur',
            type: 'number',
          },
        ],
        expectPrice: [
          { required: true, message: '请输入预期价格！', trigger: 'blur' },
          {
            pattern: /^(0\.[0-9]{2})$|^([1-9][0-9]*)$|^([1-9][0-9]*\.[0-9]{1,2})$|^0$/,
            message: '只支持大于等于0的数，允许输入两位小数',
            trigger: 'blur',
          },
          {
            max: 1000000000,
            message: '总量不能超过十亿',
            trigger: 'blur',
            type: 'number',
          },
        ],
        expectShare: [
          {
            max: 100,
            message: '请输入一个百分数',
            trigger: 'blur',
            type: 'number',
          },
          {
            pattern: /^(0\.[0-9]{2})$|^([1-9][0-9]*)$|^([1-9][0-9]*\.[0-9]{1,2})$|^0$/,
            message: '请输入一个百分数',
            trigger: 'blur',
          },
        ],
        expectQuantity: [
          { required: true, message: '请输入预期数量', trigger: 'blur' },
          {
            pattern: /^\+?[1-9]\d*$/,
            message: '请输入一个大于0的整数',
            trigger: 'blur',
          },
          {
            max: 1000000000,
            message: '总量不能超过十亿',
            trigger: 'blur',
            type: 'number',
          },
        ],
        leadsSource: [
          { required: true, message: '请选择来源', trigger: 'change' },
        ],
        appCategory: [
          { required: true, message: '请选择应用别', trigger: 'change' },
        ],
        customerName: [
          { required: true, message: '请选择客户', trigger: 'blur' },
        ],
        pmGroup: [
          { required: true, message: '请选择KAPM组', trigger: 'change' },
        ],
        pm: [{ required: true, message: '请选择pm', trigger: 'change' }],
        remark: [
          {
            max: 255,
            message: '长度不能超过255个字符',
            trigger: 'blur',
          },
        ],
        competitor: [
          {
            max: 255,
            message: '长度不能超过255个字符',
            trigger: 'blur',
          },
        ],
      },
      showButton: true,
      visibleBusinessList: false,
      visibleClueList: false,
      visibleCustomer: false,
      list: [],
      groupList: [],
      orgList: [],
      orgGroup: {},
      salesGroup: {},
    };
  },
  computed: {
    orgGroupOptions() {
      return this.$store.getters.getOrg({
        code: this.form.salesOrgCode,
        type: 'sales',
        isDict: false,
      });
    },
    customerArea() {
      return this.$store.state.dictionary.dict['customer_area'] || {};
    },
    orgKapmOptions() {
      return this.$store.getters.getOrg({
        code: this.form.salesOrgCode,
        type: 'kapm',
        isDict: false,
      });
    },
    orgOptions() {
      return this.$store.getters.getOrg({
        code: 'ltcsmsizebu',
      });
    },
    stateOptions() {
      return this.$store.state.dictionary.dict['business_status'] || {};
    },
    stateStatusOptions() {
      return {
        0: '未启动',
        1: '进行中',
        2: '已通过',
        3: '不涉及',
        4: '已失销',
      };
    },
    stageOptions() {
      return (
        this.$store.state.dictionary.dict['business_stage_process_node'] || {}
      );
    },
    applicationOptions() {
      return this.$store.state.dictionary.dict['application'] || {};
    },
    levelOptions() {
      return this.$store.state.dictionary.dict['leads_level'] || {};
    },
    sourceOptions() {
      return this.$store.state.dictionary.dict['leads_source'] || {};
    },
    showCopy() {
      return !this.showForm;
    },
    uid() {
      return this.$store.state.user.uid;
    },
    label() {
      return {
        opportunityNo: '商机编号',
        stage: '商机阶段',
        status: '商机阶段状态',
        opportunityName: '商机名称',
        leadsNo: '线索编号',
        state: '当前状态',
        leadsName: '线索名称',
        leadsSource: '来源',
        crustItemNo: '客户项目号',
        crustItemStep: '客户项目阶段',
        itemDemandNum: '客户项目需求总量',
        expectPrice: '预期价格',
        expectTime: '预期放量时间',
        expectShare: '预期份额',
        salesOrgCode: '销售组织',
        salesGroupName: '销售组',
        pmGroup: 'KAPM组',
        customerName: '客户',
        assessLevel: '评估级别',
        crustItemName: '客户项目名称',
        appCategory: '应用别',
        expectQuantity: '预期数量',
        expectCost: '预期价值',
        salesAreaName: '销售区域',
        salesName: '销售',
        pm: 'PM',
        competitor: '竞争对手',
        remark: '备注',
        createUserName: '创建人',
        createDeptName: '创建人部门',
        updateUserName: '修改人',
        creatTime: '创建时间',
        updateTime: '修改时间',
        updateDeptName: '修改人部门',
        accessory: '附件',
      };
    },
  },
  watch: {
    'form.expectQuantity': {
      handler(val) {
        this.form.expectCost = (val * this.form.expectPrice).toFixed(2);
      },
    },
    'form.expectPrice': {
      handler(val) {
        this.form.expectCost = (val * this.form.expectQuantity).toFixed(2);
      },
    },
    immediate: true,
    deep: true,
  },
  created() {
    this.getOrg();
  },
  methods: {
    numberInfo(val) {
      this.$emit('number-click', val);
    },
    async deleteFile(list) {
      const result = await getAttachmentDelete(list[list.length - 1].id);
      if (result.data.code === 0) {
        this.list = [];
      }
    },
    salesChange(val) {
      this.form.salesGroup = val;
      this.form.salesGroupCode = val.key;
      this.form.salesGroupName = val.label;
    },
    handlechange(val) {
      this.form.salesOrg = val;
      this.form.salesOrgCode = val.key;
      this.form.salesOrgName = val.label;
      this.form.pmGroup = {};
      this.form.salesGroup = {};
      const salesGroup = this.groupList.filter(
        item =>
          this.form.salesOrgName === item.ltcorg[Object.keys(item.ltcorg)[0]]
      );
      const salesList = salesGroup.map(item => item.salesgroup);
      this.salesGroup = {};
      salesList.forEach(item => {
        if (!item[Object.keys(item)[0]]) return;
        this.salesGroup[Object.keys(item)[0]] = item[Object.keys(item)[0]];
      });
    },
    handleSalesChange(val) {
      this.form.salesGroup = val;
      this.form.salesGroupCode = val.key;
      this.form.salesGroupName = val.label;
    },
    async getOrg() {
      const result = await getUserGroup(this.form.salesUserId);
      const orgs = result.data.data.org;
      this.groupList = orgs;
      this.orgList = orgs.map(item => item.ltcorg);
      this.orgList.forEach(
        item =>
          (this.orgGroup[Object.keys(item)[0]] = item[Object.keys(item)[0]])
      );
      this.form.salesOrgName = this.orgGroup[Object.keys(this.orgGroup)[0]];
      this.form.salesOrgCode = Object.keys(this.orgGroup)[0];
      const salesGroup = orgs.filter(
        item =>
          this.form.salesOrgName === item.ltcorg[Object.keys(item.ltcorg)[0]]
      );
      const salesList = salesGroup.map(item => item.salesgroup);
      salesList.forEach(item => {
        if (!item[Object.keys(item)[0]]) return;
        this.salesGroup[Object.keys(item)[0]] = item[Object.keys(item)[0]];
      });
      this.form.salesGroup.key = Object.keys(this.salesGroup)[0];
      this.form.salesGroup.label = Object.keys(this.salesGroup)[0];
      this.form.salesGroupName = this.salesGroup[
        Object.keys(this.salesGroup)[0]
      ];
      this.form.salesGroupCode = Object.keys(this.salesGroup)[0];
    },
    // 选择客户
    changeCustomer(val) {
      this.form.customerShortName = val.label;
      this.form.customerCode = val.key;
      this.form.customerName = val.customerName;
      this.form.salesAreaName = val.salesAreaName;
    },
    // 复制线索
    copyClue(val) {
      this.form.leadsName = val.leadsName;
      this.form.leadsSource = val.leadsSource;
      this.form.crustItemName = val.custItemName;
      this.form.crustItemNo = val.custItemNo;
      this.form.crustItemStep = val.custItemStep;
      this.form.itemDemandNum = val.itemDemandNum;
      this.form.expectPrice = val.expectPrice;
      this.form.expectCost = val.expectCost;
      this.form.expectQuantity = val.expectAmount;
      this.form.customerName = val.customerName;
      this.form.assessLevel = val.assessLevel;
      this.form.customerCode = val.customerCode;
      this.form.appCategory = val.appCategory;
      this.form.customerCode = val.customerCode;
      this.form.customerShortName = val.customerShortName;
      this.form.leadsNo = val.leadsNo;
      this.form.salesAreaName = val.salesAreaName;
      this.showButton = false;
    },
    // 复制商机
    copyBusiness(val) {
      this.form.leadsSource = val.leadsSource;
      this.form.crustItemName = val.crustItemName;
      this.form.crustItemNo = val.crustItemNo;
      this.form.crustItemStep = val.crustItemStep;
      this.form.itemDemandNum = val.itemDemandNum;
      this.form.expectPrice = val.expectPrice;
      this.form.expectCost = val.expectCost;
      this.form.expectQuantity = val.expectQuantity;
      this.form.pmGroupCode = val.pmGroupCode;
      this.form.customerName = val.customerName;
      this.form.assessLevel = val.assessLevel;
      this.form.appCategory = val.appCategory;
      this.form.customerCode = val.customerCode;
      this.form.customerShortName = val.customerShortName;
      this.form.opportunityName = val.opportunityName;
      this.form.expectTime = val.expectTime;
      this.form.expectShare = +val.expectShare;
      this.form.competitor = val.competitor;
      this.form.remark = val.remark;
      this.form.pmGroup.key = val.pmGroupCode;
      this.form.pmGroup.label = val.pmGroupName;
      this.form.pm.key = val.pmUserId;
      this.form.pm.label = val.pmName;
      this.form.salesOrg.key = val.salesOrgCode;
      this.form.salesOrg.label = val.salesOrgName;
      this.form.salesGroup.label = val.salesGroupName;
      this.form.salesGroup.key = val.salesGroupCode;
    },
    validate() {
      return new Promise(resolve => {
        this.$refs.form.validate(valid => {
          resolve(valid);
        });
      });
    },
    upload() {
      this.$refs.upload?.uploader();
      console.log(this.list, '---');
    },
    handlefocus() {
      if (this.form.customer === '') {
        this.$message.error('请选择客户!');
      }
    },
    handleDeadLineOk(value) {
      const formatTime = monent(value).format('YYYY-MM-DD 23:59:59');
      this.form.expectTime = formatTime;
    },
    handleDeadLineChange(value) {
      const formatTime = monent(value).format('YYYY-MM-DD 23:59:59');
      this.form.expectTime = formatTime;
    },
    handleSelectChange(val, key) {
      this.form[key] = val;
      if (key === 'pmGroup') {
        this.form.pm = '';
      }
    },
  },
};
</script>

<style lang="less" scoped>
.item {
  display: flex;
  justify-content: space-between;
  .item-left,
  .item-right {
    width: 48%;
    display: inline-block;
  }
}

.poros-form-item {
  display: flex;
  flex-wrap: nowrap;
  //   margin-bottom: 10px;
}
// .item {
//   width: 48%;
//   display: inline-block;
// }
/deep/ .poros-form-item-label {
  width: 120px;
  margin-right: 20px;
}
/deep/ .poros-form-item-control-wrapper {
  width: calc(100% - 250px);
}
.form-item {
  position: relative;
  .copy-clue {
    position: absolute;
    top: 0;
    right: 0;
    transform: translate(110%, -25%);
  }
  .searchIcon {
    position: absolute;
    top: 0;
    right: 5px;
  }
}
</style>
